//
//  XLMShareSdkTool.m
//  xiaoLeMusic
//
//  Created by wukong on 2018/8/29.
//  Copyright © 2018年 xiaoLe. All rights reserved.
//

#import "XLMShareSdkTool.h"

///*****ShareSDK********/
//#define K_ShareSDK_AppKey      @"27985dba46cd5"
//#define K_ShareSDK_AppSecret   @"8d3d5a8c20794b047a92d0e7744ccb73"
////QQAppId16进制 41e2c9d5   QQ41E2C9D5
////新浪
//#define K_Sina_AppKey    @"3834311617"
//#define K_Sina_AppSecret @"8a88095b6f67e16dd04d12122b0b19a9"
//#
////QQ
//#define K_QQ_AppId       @"1107594908"
//#define K_QQ_AppKey      @"9TqB1MpQXyWyqRYE"
////微信
//#define K_WX_AppID       @"wx66dbf2364ba71aed"
//#define K_WX_AppSecret   @"2e776349825368e7d946c4a0d7568612"
//#define K_Share_Url      @"http://www.sharesdk.cn"

static  XLMShareSdkTool *toolManager;
@interface XLMShareSdkTool()

@property (strong, nonatomic) NSMutableDictionary *shareParams;
@property (copy, nonatomic) shareSuccessBlock successBlock;
@property (copy, nonatomic) shareFailBlock failBlock;


@end

@implementation XLMShareSdkTool

+(XLMShareSdkTool *) shareInstance{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        toolManager = [[XLMShareSdkTool alloc]init];
    });
    return toolManager;
}

- (void)dealloc {
    self.delegate = nil;
    //    [super dealloc];
}

#pragma mark - ShareSDK 注册

+(void)registerShare{
    //registerApp 初始化SDK并且初始化第三方平台
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeWechat),
                                        ]
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
//             case SSDKPlatformTypeQQ:
//                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
//                 break;
//             case SSDKPlatformTypeSinaWeibo:
//                  [ShareSDKConnector connectWeibo:[WeiboSDK class]];
//                  break;
             default:
                 break;
         }
     }
     onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
                 
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:kAppKey_Wechat
                                       appSecret:kSecret_Wechat];
                 break;
             case SSDKPlatformTypeSinaWeibo:
             default:
                 break;
         }
     }];
}
#pragma mark- 分享

#pragma mark 分享文件代码(仅支持微信好友)
/**
 *  分享图片、文本、URL等信息(微信朋友圈)
 */
+(void) shareWechatTimelineContentWithShareContentType:(SSDKContentType)shareContentType contentImage:(id)contentImage onStateChanged:(doneblock)block{
    
    
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    /*
     分享图片时：
     *  设置type为SSDKContentTypeImage, 非gif图片时：填入title和image参数，如果为gif图片则需要填写title和emoticonData参数
     */
    //    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    [shareParams SSDKSetupShareParamsByText:@""
                                     images:contentImage
                                        url:nil
                                      title:@"个人主页"
                                       type:SSDKContentTypeImage];
    
    [ShareSDK share:SSDKPlatformSubTypeWechatTimeline parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        block(state);
    }];
}


+(void)shareInviteCodeWithShareContentType:(SSDKPlatformType)sharePlatformType
                                   content:(NSString *)content
                            onStateChanged:(doneblock)block{
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
  
    [shareParams SSDKSetupShareParamsByText:content
                                     images:nil
                                        url:nil
                                      title:@"红草视界"
                                       type:SSDKContentTypeText];
    
    [ShareSDK share:sharePlatformType parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        block(state);
    }];
}


//分享视频到其他客户端
+ (void)shareVedioWithPlatformType:(SSDKPlatformType)platformType
                              Text:(NSString *)text
                             title:(NSString *)title
                               url:(NSString *)url
                        thumbImage:(id)thumbImage
                             image:(id)image
                      musicFileURL:(NSURL *)musicFileURL
                           extInfo:(NSString *)extInfo
                          fileData:(id)fileData
                      emoticonData:(id)emoticonData
               sourceFileExtension:(NSString *)fileExtension
                    sourceFileData:(id)sourceFileData
                              type:(SSDKContentType)type
                    onStateChanged:(doneblock)block{
    
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    /*
     分享图片时：
     *  设置type为SSDKContentTypeImage, 非gif图片时：填入title和image参数，如果为gif图片则需要填写title和emoticonData参数
     */
//    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    [shareParams SSDKSetupShareParamsByText:text
                                     images:IMAGE_NAMED(@"icon1")
                                        url:[NSURL URLWithString:url]
                                      title:@"红草视频"
                                       type:SSDKContentTypeVideo];
//    [shareParams SSDKSetupWeChatParamsByText:@"test"
//                                       title:SafeStr(title)
//                                         url:[NSURL URLWithString:url]
//                                  thumbImage:thumbImage
//                                       image:nil
//                                musicFileURL:nil
//                                     extInfo:nil
//                                    fileData:nil
//                                emoticonData:nil
//                         sourceFileExtension:nil
//                              sourceFileData:nil
//                                        type:SSDKContentTypeVideo
//                          forPlatformSubType:SSDKPlatformTypeWechat];
    
    [ShareSDK share:platformType parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        block(state);
    }];
    
}


//分享到其他客户端
+ (void)shareWithPlatformType:(SSDKPlatformType)platformType onStateChanged:(doneblock)block {
    
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    /*
     分享图片时：
     *  设置type为SSDKContentTypeImage, 非gif图片时：填入title和image参数，如果为gif图片则需要填写title和emoticonData参数
     */
    [shareParams SSDKSetupWeChatParamsByText:nil
                                       title:@""
                                         url:nil
                                  thumbImage:nil
                                       image:IMAGE_NAMED(@"被邀请")
                                musicFileURL:nil
                                     extInfo:nil
                                    fileData:nil
                                emoticonData:nil
                         sourceFileExtension:nil
                              sourceFileData:nil
                                        type:SSDKContentTypeImage
                          forPlatformSubType:platformType];
    
    [ShareSDK share:platformType parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        block(state);
    }];
}


//单个分享
+(void)shareWithPlatformType:(SSDKPlatformType)platformType{
//    AA_WEAK_MAKE(toolManager) weakToolManager = toolManager;

//    if(platformType == SSDKPlatformTypeSinaWeibo){
//        NSArray *temparr = [toolManager.shareParams objectForKey:@"images"];
//        if(temparr.count == 0){
//            [toolManager.shareParams  removeObjectForKey:@"images"];
//        }
//    }
    [ShareSDK share:platformType parameters:toolManager.shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
            switch (state) {
                case SSDKResponseStateSuccess:{
                   toolManager.successBlock();
                    
                }
                    break;
                case SSDKResponseStateFail:{
                      toolManager.failBlock(error.description);
//                    failure([NSString stringWithFormat:@"%@",error]);
                   
                }
                     break;
                case SSDKResponseStateCancel:{
//                     toolManager.failBlock(@"分享取消");
//                    otherResponseStatus(SSDKResponseStateCancel);
                }
                    break;
                default:
                    break;
            }
//            if (state != SSDKResponseStateBegin){
//                  toolManager.failBlock(error.description);
//            }
    }];
}

#pragma mark ====第三方登录====

+(void) thirdLoginWithWeChatResult{
    //构造SendAuthReq结构体
//    toolManager.loginBlock = loginResult;
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"App";
   BOOL suc = [WXApi sendReq:req];
    NSLog(@"ee");
}

+(void)thirdLoginWithType:(SSDKPlatformType)type result:(ThirdLoginResult)loginResult{
    
//    [ShareSDK cancelAuthorize:type];
    [ShareSDK authorize:type settings:nil onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        
        switch (state) {
            case SSDKResponseStateSuccess:
            {
                if(type == SSDKPlatformTypeWechat){
                    NSString *code = [[NSUserDefaults standardUserDefaults] objectForKey:XLMThirdLoginWithWeChatCode];
                    if(code){
                        loginResult(YES,@{@"code":code,
                                          @"token":@""
                                         });
                    }else{
                        loginResult(NO,@{@"message":@"授权失败"});
                    }
                }else{
                    NSDictionary *dic = @{@"token":user.credential.token,
                                          @"code":user.credential.uid
                                          };
                    loginResult(YES,dic);
                }
            }
                break;
            case SSDKResponseStateFail:
            {
                loginResult(NO,@{@"message":error.localizedDescription});
            }
                break;
            default:
                break;
        }
    }];
//    [ShareSDK getUserInfo:type onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
//        switch (state) {
//            case SSDKResponseStateSuccess:
//            {
//                loginResult(YES,nil);
//            }
//                break;
//            case SSDKResponseStateFail:
//            {
//                loginResult(NO,error.localizedDescription);
//            }
//               break;
//            default:
//                break;
//        }
//    }];
}

#pragma mark -weixin delegate
- (void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *esp = (SendAuthResp *)resp;
        if(resp.errCode == 0){
            if(toolManager.loginBlock){
                toolManager.loginBlock(YES, @{@"code":esp.code});
            }
        }else{
            toolManager.loginBlock(NO, @{@"message":@"授权失败"});
        }
    }else{
        toolManager.loginBlock(NO, @{@"message":@"授权失败"});
    }
}
//
//- (void)onReq:(BaseReq *)req {
//   NSLog(@"eee");
//}

@end
